<template>
  <div class="tags-view-container" id="guide-tags-view">
    <router-link
      class="tags-view"
      v-for="(tag, index) in tagsViewList"
      :key="tag.fullPath"
      :class="isActive(tag) ? 'active' : ''"
      :to="tag.path"
      :style="{
        backgroundColor: isActive(tag) ? $store.getters.cssVar.menuBg : '',
        borderColor: isActive(tag) ? $store.getters.cssVar.menuBg : ''
      }"
      @contextmenu.prevent="onContextMenu(index, $event)"
    >
      {{ tag.title }}
      <i class="el-icon-close" v-if="!isActive(tag)" @click.prevent.stop="closeTag(index)" />
    </router-link>

    <context-menu
      v-show="contextMenuIsShow"
      :index="contextMenuIndex"
      :style="contextMenuPosition"
    />
  </div>
</template>

<script setup>
import ContextMenu from './ContextMenu'
import { computed, ref, watch } from 'vue'
import { useRoute } from 'vue-router'
import { useStore } from 'vuex'
const route = useRoute()
const store = useStore()
const tagsViewList = computed(() => store.getters.tagsViewList)
const contextMenuIsShow = ref(false)
const contextMenuIndex = ref(0)
const contextMenuPosition = ref({
  left: 0,
  top: 0
})
const isActive = (tag) => {
  return route.path === tag.path
}
const closeTag = (index) => {
  store.commit('app/removeTagsView', { type: 'index', index })
}
const onContextMenu = (index, $events) => {
  const { x, y } = $events
  contextMenuPosition.value.left = `${x}px`
  contextMenuPosition.value.top = `${y}px`
  contextMenuIndex.value = index
  contextMenuIsShow.value = true
}
const closeContextMenu = () => {
  contextMenuIsShow.value = false
}

watch(contextMenuIsShow, (val) => {
  if (val) {
    document.addEventListener('click', closeContextMenu)
  } else {
    document.removeEventListener('click', closeContextMenu)
  }
})
</script>

<style lang="scss" scoped>
.tags-view-container {
  display: flex;
  flex-wrap: wrap;
  height: 37px;
  overflow: hidden;
  padding: 0 20px;
  box-shadow: 0 4px 8px rgba(0, 0, 0, .1);
  .tags-view {
    transform: all .4s;
    padding: 5px 8px;
    height: 19px;
    line-height: 19px;
    margin: 4px 0;
    border: 1px solid #d8dce5;
    border-radius: 2px;
    margin-right: 7px;
    font-size: 14px;
    color: #495060;
    font-size: 12px;
    &.active {
      background: $menuBg;
      color: #ffffff;
      &::before {
        content: '';
        display: inline-block;
        width: 8px;
        height: 8px;
        border-radius: 50%;
        background: #ffffff;
        margin-right: 8px;
      }
    }
    i {
      padding: 2px;
      transform: all .4s;
      &:hover {
        background: #a6a9ad;
        color: #fff;
        border-radius: 50%;
      }
    }
  }
}
</style>
